import { GraphQLError } from 'graphql'
import moment = require('moment')
import { Reservation } from '../../Models/Reservation'
import checkAuth from '../../util/check-auth'
const reservationResolvers = {
  Mutation: {
    async createReservation(
      _: any,
      { reservationInput: { arrivalDate, arrivalTime, tableSize } }: any,
      context: any
    ) {
      // 1、获取user用户信息
      // 2、查询当天是否重复预订
      // 3、写入数据库(拼接预订人信息)
      const user = checkAuth(context)
      const res = await Reservation.findOne({ arrivalDate })
      if (res) {
        throw new GraphQLError('The user has a reservation for the day')
      }
      let newReservation = new Reservation({
        arrivalDate,
        arrivalTime,
        tableSize,
        status: 2,
        createdAt: moment().utcOffset(8).format('YYYY-MM-DD HH:mm:ss'),
        ...user
      })
      newReservation = await newReservation.save()
      return newReservation
    },
    async updateReservation(_: any, { reservationId, status }: any, context: any) {
      checkAuth(context)
      console.log(reservationId);
      const res = await Reservation.findByIdAndUpdate(reservationId, { status }).lean()
      return { ...res, id: res._id }
    },
    async deleteReservation(_: any, { reservationId }: any, context: any) {
      checkAuth(context)
      const res = await Reservation.findByIdAndDelete(reservationId).lean()
      return { ...res, id: res._id }
    }
  },
  Query: {
    async getReservation(_: any, { phone }: any, context: any) {
      const user = checkAuth(context)
      const query: ReservationQuery = {}
      if (user.type === 'customer') query.phone = user.phone
      const res = await Reservation.find(query).lean()
      return res.map((n) => {
        n.id = n._id
        return n
      })
    },
  },
}

interface ReservationQuery {
  phone?: string
}
export { reservationResolvers }